package com.suyl.candy.weather.core.confige;

import com.suyl.candy.weather.core.interceptor.TokenInterceptor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Log4j2
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    TokenInterceptor tokenInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //1.加入的顺序就是拦截器执行的顺序，
        //2.按顺序执行所有拦截器的preHandle
        //3.所有的preHandle 执行完再执行全部postHandle 最后是postHandle
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(tokenInterceptor);
        // 排除拦截
        interceptorRegistration.excludePathPatterns("/city/**", "/search/**", "/common/**");
        // 拦截配置
        interceptorRegistration.addPathPatterns("/**");

        /*InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        //排除配置
        addInterceptor.excludePathPatterns("/userLogin", "/css/**", "/images/**", "/js/**", "/login.html");
        //拦截配置
        addInterceptor.addPathPatterns("/**");*/
    }

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }

    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
            HttpSession session = request.getSession();
            //判断是否已有该用户登录的session
            if (session.getAttribute("username") != null) {
                return true;
            } else {
                log.info("没有session");
//                response.sendRedirect("http://localhost:8080/login.html");
                return false;
            }
        }
    }
}
